package com.aisino.api.controller;

import com.aisino.api.model.*;
import com.aisino.api.service.DrugStandardService;
import com.aisino.api.util.RedisUtil;
import com.aisino.api.util.XssEscapeUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/v1")
public class DrugStandardController {

    private static final Logger logger = LoggerFactory.getLogger(DrugStandardController.class);

    @Autowired
    private DrugStandardService drugStandardService;
    @Autowired
    private RedisUtil redisUtil;
    /**
     * 获取药品标准库列表接口
     * @param request 请求参数
     * @return 药品标准库数据
     */
    @PostMapping("/getDrugList")
    public ResponseEntity<DrugStandardResponse> getDrugList(@RequestBody(required = false) DrugStandardRequest request) {
        logger.info("Received request to get drug list");

        // 检查请求体是否存在
        if (request == null) {
            logger.warn("Request body is missing");
            DrugStandardResponse response = new DrugStandardResponse();
            response.setCode(400);
            response.setMsg("请求体不能为空");
            return buildSecureResponseEntity(response, HttpStatus.BAD_REQUEST);
        }

        try {
            logger.info("Processing request with reqId: {}", request.getReqId());

            // 设置默认reqId（如果未提供）
            if (request.getReqId() == null || request.getReqId().isEmpty()) {
                request.setReqId(UUID.randomUUID().toString());
            }

            // 调用服务获取药品数据
            DrugStandardResponse result = drugStandardService.getDrugList(request);

            logger.info("Successfully processed request with reqId: {}", request.getReqId());
            return buildSecureResponseEntity(result, HttpStatus.OK);
        } catch (Exception e) {
            logger.error("Error processing request: ", e);
            DrugStandardResponse response = new DrugStandardResponse();
            response.setCode(500);
            response.setMsg("系统错误: " + e.getMessage());
            if (request != null) {
                response.setReqId(request.getReqId());
            }
            return buildSecureResponseEntity(response, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * 上传药品入库信息
     * @param request 请求参数
     * @return 上传结果
     */
    @PostMapping(value = "/uploadDrugIn",name = "上传药品入库信息")
    public ResponseEntity<DrugStandardResponse> uploadDrugIn(@RequestBody(required = false) DrugInRequest request) {
        String transactionId = request.getReqId();
        logger.info("Processing uploadDrugIn request with reqId: {}", transactionId);
        // 检查是否已经处理过
        if (redisUtil.isProcessed(transactionId)) {
            DrugStandardResponse response = new DrugStandardResponse();
            response.setReqId(request.getReqId());
            response.setCode(ResultCode.SUCCESS.getCode());
            response.setMsg("重复的reqId 系统已忽略本次请求");
            return buildSecureResponseEntity(response, HttpStatus.OK);
        }
        DrugStandardResponse response = drugStandardService.uploadDrugIn(request);

        logger.info("Completed uploadDrugIn request with reqId: {}, code: {}, msg: {}",
                request.getReqId(), response.getCode(), response.getMsg());
        // 标记为已处理
        redisUtil.markAsProcessed(transactionId);
        return buildSecureResponseEntity(response, HttpStatus.OK);
    }

    /**
     * 药品库存信息上传接口
     * @param request 请求参数
     * @return 上传结果
     */
    @PostMapping(value = "/uploadDrugInvinfo",name = "库存信息上传")
    public ResponseEntity<DrugStandardResponse> uploadDrugInventory(@RequestBody(required = false) DrugInventoryRequest request) {
        String transactionId = request.getReqId();
        logger.info("Processing uploadDrugInvinfo request with reqId: {}", transactionId);
        // 检查是否已经处理过
        if (redisUtil.isProcessed(transactionId)) {
            DrugStandardResponse response = new DrugStandardResponse();
            response.setReqId(request.getReqId());
            response.setCode(ResultCode.SUCCESS.getCode());
            response.setMsg("重复的reqId 系统已忽略本次请求");
            return buildSecureResponseEntity(response, HttpStatus.OK);
        }

        DrugStandardResponse response = drugStandardService.uploadDrugInventory(request);

        logger.info("Completed uploadDrugInvinfo request with reqId: {}, code: {}, msg: {}",
                request.getReqId(), response.getCode(), response.getMsg());
        // 标记为已处理
        redisUtil.markAsProcessed(transactionId);
        return buildSecureResponseEntity(response, HttpStatus.OK);
    }

    /**
     * 药品出库信息上传接口
     * @param request 请求参数
     * @return 上传结果
     */
    @PostMapping(value = "/uploadDrugOut", name = "药品出库信息上传")
    public ResponseEntity<DrugStandardResponse> uploadDrugOut(@RequestBody(required = false) DrugOutRequest request) {
        String transactionId = request.getReqId();
        logger.info("Processing uploadDrugOut request with reqId: {}", transactionId);
        // 检查是否已经处理过
        if (redisUtil.isProcessed(transactionId)) {
            DrugStandardResponse response = new DrugStandardResponse();
            response.setReqId(request.getReqId());
            response.setCode(ResultCode.SUCCESS.getCode());
            response.setMsg("重复的reqId 系统已忽略本次请求");
            return buildSecureResponseEntity(response, HttpStatus.OK);
        }
        DrugStandardResponse response = drugStandardService.uploadDrugOut(request);

        logger.info("Completed uploadDrugOut request with reqId: {}, code: {}, msg: {}",
                request.getReqId(), response.getCode(), response.getMsg());
        // 标记为已处理
        redisUtil.markAsProcessed(transactionId);
        return buildSecureResponseEntity(response, HttpStatus.OK);
    }

    /**
     * 新增药品信息接口
     * @param request 请求参数
     * @return 上传结果
     */
    @PostMapping(value = "/uploadDrugInfo", name = "新增药品信息")
    public ResponseEntity<DrugInfoResponse> uploadDrugInfo(@RequestBody(required = false) DrugInfoRequest request) {
        String transactionId = request.getReqId();
        logger.info("Processing uploadDrugInfo request with reqId: {}", transactionId);
//        // 检查是否已经处理过
//        if (redisUtil.isProcessed(transactionId)) {
//            DrugInfoResponse response = new DrugInfoResponse();
//            response.setReqId(request.getReqId());
//            response.setCode(ResultCode.SUCCESS.getCode());
//            response.setMsg("重复的reqId 系统已忽略本次请求");
//            return buildSecureResponseEntity(response, HttpStatus.OK);
//        }
        DrugInfoResponse response = drugStandardService.uploadDrugInfo(request);

        logger.info("Completed uploadDrugInfo request with reqId: {}, code: {}, msg: {}",
                request.getReqId(), response.getCode(), response.getMsg());
        // 标记为已处理
//        redisUtil.markAsProcessed(transactionId);
        return buildSecureResponseEntity(response, HttpStatus.OK);
    }


    /**
     * 温湿度信息上传接口
     * @param request 请求参数
     * @return 上传结果
     */
    @PostMapping(value = "/uploadHumitureInfo", name = "温湿度信息上传")
    public ResponseEntity<DrugStandardResponse> uploadHumitureInfo(@RequestBody(required = false) HumitureInfoRequest request) {
        String transactionId = request.getReqId();
        logger.info("Processing uploadHumitureInfo request with reqId: {}", transactionId);

        // 检查是否已经处理过
        if (redisUtil.isProcessed(transactionId)) {
            DrugStandardResponse response = new DrugStandardResponse();
            response.setReqId(request.getReqId());
            response.setCode(ResultCode.SUCCESS.getCode());
            response.setMsg("重复的reqId 系统已忽略本次请求");
            return buildSecureResponseEntity(response, HttpStatus.OK);
        }

        DrugStandardResponse response = drugStandardService.uploadHumitureInfo(request);

        logger.info("Completed uploadHumitureInfo request with reqId: {}, code: {}, msg: {}",
                request.getReqId(), response.getCode(), response.getMsg());
        // 标记为已处理
        redisUtil.markAsProcessed(transactionId);
        return buildSecureResponseEntity(response, HttpStatus.OK);
    }

    /**
     * 维护下属门店接口
     * @param request 请求参数
     * @return 处理结果
     */
    @PostMapping(value = "/editSubStore", name = "维护下属门店信息")
    public ResponseEntity<DrugStandardResponse> editSubStore(@RequestBody Map<String, String> request) {
        logger.info("Processing editSubStore request with reqId: {}", request.get("reqId"));

        DrugStandardResponse response = drugStandardService.editSubStore(request);

        logger.info("Completed editSubStore request with reqId: {}, code: {}, msg: {}",
                request.get("reqId"), response.getCode(), response.getMsg());

        return buildSecureResponseEntity(response, HttpStatus.OK);
    }

    /**
     * 门店基本信息完善接口
     * @param request 请求参数
     * @return 处理结果
     */
    @PostMapping(value = "/editSubStoreInfo", name = "门店基本信息完善")
    public ResponseEntity<DrugStandardResponse> editSubStoreInfo(@RequestBody SubStoreInfoRequest request) {
        logger.info("Processing editSubStoreInfo request with reqId: {}", request.getReqId());

        DrugStandardResponse response = drugStandardService.editSubStoreInfo(request);

        logger.info("Completed editSubStoreInfo request with reqId: {}, code: {}, msg: {}",
                request.getReqId(), response.getCode(), response.getMsg());

        return buildSecureResponseEntity(response, HttpStatus.OK);
    }

    /**
     * 构建带安全头部的响应实体
     * @param body 响应体
     * @param status HTTP状态码
     * @return 带安全头部的响应实体
     */
    private <T> ResponseEntity<T> buildSecureResponseEntity(T body, HttpStatus status) {
        HttpHeaders headers = new HttpHeaders();
        headers.set("X-Content-Type-Options", "nosniff");
        headers.set("Content-Security-Policy", "default-src 'self'");
        headers.set("X-Frame-Options", "DENY");
        headers.set("X-XSS-Protection", "1; mode=block");
        body = XssEscapeUtil.escapeObject(body);
        return new ResponseEntity<>(body, headers, status);
    }
}
